package fhp.hlhj.giantfold.activity.malls

import android.annotation.SuppressLint
import android.content.Intent
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.webkit.*
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcMyOrdersPage
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.lzy.okgo.model.HttpParams
import fhp.hlhj.giantfold.BaseActivity
import fhp.hlhj.giantfold.Contents
import fhp.hlhj.giantfold.R
import fhp.hlhj.giantfold.activity.orders.TiketAty
import fhp.hlhj.giantfold.activity.user.OrderAty
import fhp.hlhj.giantfold.adapter.ViewPagerAdp
import fhp.hlhj.giantfold.customView.OrderPop
import fhp.hlhj.giantfold.dbBean.Oder
import fhp.hlhj.giantfold.fragment.OrderFgm
import fhp.hlhj.giantfold.fragment.TbOrderFgm
import fhp.hlhj.giantfold.interfaces.ICreateOrder
import fhp.hlhj.giantfold.interfaces.ITaoBaoOrder
import fhp.hlhj.giantfold.javaBean.BaseBean
import fhp.hlhj.giantfold.javaBean.InJavaScriptLocalObj
import fhp.hlhj.giantfold.presenter.OrderPresenter
import fhp.hlhj.giantfold.presenter.TaoBaoOrderPresenter
import fhp.hlhj.giantfold.utils.LogUtil
import fhp.hlhj.giantfold.utils.MyUtils
import kotlinx.android.synthetic.main.activity_order_list_aty.*
import org.jsoup.Jsoup
import org.litepal.LitePal
import org.litepal.crud.DataSupport
import kotlin.text.Typography.amp

class TBOrderListAty : BaseActivity(), ITaoBaoOrder, ICreateOrder, OrderPop.onPopSelect, ViewPager.OnPageChangeListener, TabLayout.OnTabSelectedListener {


    private val obj:InJavaScriptLocalObj=InJavaScriptLocalObj()
    private lateinit var presenter:TaoBaoOrderPresenter
    override fun getContentId(): Int = R.layout.activity_order_list_aty
    private lateinit var orderPresenter: OrderPresenter
    private var enterType =0
    private var isFirst=true


    private lateinit var orderPop: OrderPop
    private var fragments=ArrayList<Fragment>()
    private lateinit var allFgm: TbOrderFgm
    private lateinit var goingFgm: TbOrderFgm
    private lateinit var savedFgm: TbOrderFgm
    private lateinit var uselessFgm: TbOrderFgm
    private lateinit var toFlipFgm: TbOrderFgm
    private lateinit var pagerAdp: ViewPagerAdp


    override fun initView() {
        enterType=intent.getIntExtra("enterType", 0)
        orderPresenter= OrderPresenter(this)
        presenter= TaoBaoOrderPresenter(this)
        presenter.showUi()
        dowork()

        orderPop=OrderPop(this,this)
        allFgm= TbOrderFgm.newInstece("全部")
        goingFgm= TbOrderFgm.newInstece("进行中")
        savedFgm= TbOrderFgm.newInstece("已存入")
        uselessFgm=TbOrderFgm.newInstece("已失效")
        toFlipFgm= TbOrderFgm.newInstece("待翻牌")

        fragments.add(allFgm)
        fragments.add(goingFgm)
        fragments.add(savedFgm)
        fragments.add(uselessFgm)
        fragments.add(toFlipFgm)

        pagerAdp= ViewPagerAdp(supportFragmentManager,fragments)

        viewPager.adapter=pagerAdp






        btExit.setOnClickListener {
            finish()
        }
    }

    override fun initListener() {
        viewPager.addOnPageChangeListener(this)
        tabLayout.addOnTabSelectedListener(this)

        btExit.setOnClickListener {
            finish()
        }

    }
    private fun dowork() {
        Thread(Runnable {
            while (true) {
                try {
                    Thread.sleep(500)
                    if (Contents.htmlStr!=null){
                        if (isFirst){
                            isFirst=false

                            if (intent.getIntExtra("et",0)==1){
                                val list = Contents.htmlStr?.split(" <li> ")
                                val singleOderStr = list!![1]
                                val params = HttpParams()
                                val orderId = singleOderStr.split("div class=\"module ")[1].substring(0, 18)
                                val goodName = singleOderStr.split("<h3 class=\"title\">")[1].split("</h3>")[0]
                                val status = singleOderStr.split("<p class=\"h\">")[1].split("</p>")[0]

                                params.put("order_id", orderId)
                                params.put("user_id",Contents.userId)
                                params.put("product_name", goodName)
                                params.put("actual_amount",singleOderStr.split("<p class=\"price\">￥")[1].split("</p>")[0].toFloat())
                                params.put("number",singleOderStr.split("<p class=\"nums\">x")[1].split("</p>")[0])
                                params.put("status", 2)
//                            params.put("status", status)
                                params.put("item_id",intent.getStringExtra("pid"))
                                params.put("b_type","taobao")
                                params.put("type","0")
                                params.put("time",MyUtils.timeStampToStr(System.currentTimeMillis()))
                                params.put("tkjd_sp","0")
                                orderPresenter.createOder(params)
                                break
                            }else if (intent.getIntExtra("et",0)==5){

                                val list = Contents.htmlStr?.split(" <li> ")
                                val singleOderStr = list!![1]
                                val params = HttpParams()
                                val orderId = singleOderStr.split("div class=\"module ")[1].substring(0, 18)
                                val goodName = singleOderStr.split("<h3 class=\"title\">")[1].split("</h3>")[0]
                                val status = singleOderStr.split("<p class=\"h\">")[1].split("</p>")[0]

                                params.put("order_id", orderId)
                                params.put("user_id",Contents.userId)
                                params.put("product_name", goodName)
                                params.put("actual_amount",singleOderStr.split("<p class=\"price\">￥")[1].split("</p>")[0].toFloat())
                                params.put("number",singleOderStr.split("<p class=\"nums\">x")[1].split("</p>")[0])
                                params.put("status", 2)
//                            params.put("status", status)
                                params.put("item_id",intent.getStringExtra("pid"))
                                params.put("b_type","taobao")
                                params.put("type","0")
                                params.put("commission_rate",intent.getStringExtra("rate"))
                                params.put("time",MyUtils.timeStampToStr(System.currentTimeMillis()))
                                params.put("tkjd_sp","1")
                                params.put("product_pic_url",intent.getStringExtra("imgurl"))
                                orderPresenter.createOder(params)
                            }
                            else{
                                val database = LitePal.getDatabase()
                                val orderList = DataSupport.findAll(Oder::class.java)
                                val htmlList = Contents.htmlStr?.split(" <li> ")
                                if (htmlList != null) {
                                    for (i in htmlList.indices){
                                        if (i!=0){
                                            val singOder = htmlList[i]
                                            LogUtil.log("此次的字符窜为$singOder")
                                            val orderId = singOder.split("<div class=\"module ")[1].substring(0, 18)
                                            val status = singOder.split("<p class=\"h\">")[1].split("</p>")[0]
                                            var isThereHas=false
                                            for (j in orderList.indices){
                                                if (orderId.equals(orderList[j].orderStr)){
                                                    LogUtil.log("发现订单号一样的订单$status")
                                                    isThereHas=true
                                                    if (status.equals(orderList[j].status)){
                                                    }else{
                                                        LogUtil.log("改订单的状态改变了")
                                                        var stype=-1
                                                        if (status.contains("成功")){
                                                            stype=1
                                                        }else if (status.contains("已付款")){
                                                            stype=2
                                                        }else if (status.contains("关闭")){
                                                            stype=4
                                                        }else if (status.contains("退款")){
                                                            stype=4
                                                        }


                                                        LogUtil.log("订单状态有更新，修改订单"+orderId)
                                                        val httpParams = HttpParams()
                                                        httpParams.put("user_id",Contents.userId)
                                                        httpParams.put("order_id",orderId)
                                                        httpParams.put("status",stype)
                                                        httpParams.put("b_type","taobao")
                                                        orderPresenter.changeOrder(httpParams)

                                                        val dbOrder = orderList[j]
                                                        dbOrder.status=status
                                                        dbOrder.save()
                                                    }
                                                }
                                            }
                                            if (!isThereHas){
                                                LogUtil.log("数据库没有此订单，开始新建")
                                                val oder = Oder()
                                                oder.orderStr=orderId
                                                oder.status=status
                                                oder.type="taobao"
                                                oder.save()

                                                val httpParams = HttpParams()
                                                httpParams.put("user_id",Contents.userId)
                                                httpParams.put("order_id",orderId)
                                                httpParams.put("status",status)
                                                httpParams.put("b_type","taobao")
                                                orderPresenter.changeOrder(httpParams)
                                            }
                                        }
                                    }

                                }
                                break
                            }
                        }

                    }else{
                        webView.post(Runnable {

//                            presenter.showUi()
                        })
                    }

                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

            }
        }).start()
    }



    @SuppressLint("AddJavascriptInterface")
    override fun showUI() {
        val ordersPage = AlibcMyOrdersPage(0, true)
        val params = AlibcShowParams(OpenType.Auto, false)

        val settings = webView.settings
        webView.addJavascriptInterface(InJavaScriptLocalObj(),"java_obj")
        settings.javaScriptEnabled = true
        settings.useWideViewPort = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        settings.loadWithOverviewMode = false
        settings.defaultFontSize = 50

        val client = object : WebViewClient(){
            override fun onPageFinished(view: WebView, url: String?) {
                view.loadUrl("javascript:window.java_obj.showSource("
                        + "document.getElementsByTagName('html')[0].innerHTML);")
                super.onPageFinished(view, url)
            }
        }
        webView.webViewClient=client
//        webView.loadUrl("")
        AlibcTrade.show(this,webView,client,null,ordersPage,params,null,null,object : AlibcTradeCallback {
            override fun onFailure(p0: Int, p1: String?) {
                LogUtil.log("打开失败$p0$p1")
            }

            override fun onTradeSuccess(p0: AlibcTradeResult?) {
            }

        })
    }

    override fun changeOrder(baseBean: BaseBean) {

    }

    override fun onDestroy() {
        super.onDestroy()
        Contents.htmlStr=null
    }

    override fun createOrder(baseBean: BaseBean) {
        if (baseBean.code==200){

        }else{
            if (baseBean.msg.equals("已存在.")){
            }else{
            }
        }
    }

    override fun onTabReselected(p0: TabLayout.Tab?) {
    }

    override fun onTabUnselected(p0: TabLayout.Tab?) {
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        val position = tab?.position
        if (position != null) {
            viewPager.currentItem = position
        }

    }

    override fun onPageScrollStateChanged(p0: Int) {
    }

    override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
    }

    override fun onPageSelected(p0: Int) {
        tabLayout.getTabAt(p0)?.select()

    }

    override fun jzOrder() {
        this.startActivity(Intent(this, OrderAty::class.java))
    }

    override fun aliOrder() {
    }

    override fun jdOrder() {
        this.startActivity(Intent(this,JdOrderListAty::class.java))

    }

    override fun xpOrder() {
        this.startActivity(Intent(this, TiketAty::class.java))

    }
}
